<template>
  <div class="main-box">
    <TreeFilter
      ref="treeFilter"
      label="orgName"
      :title="$t('message.orgInfo.title')"
      :default-value="initParam.orgId"
      :data="orgTree"
      :default-expand="false"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTableRef"
        title="用户列表"
        :columns="columns"
        :request-api="userApi.page"
        :init-param="initParam"
        :data-callback="dataCallback"
      >
        <template #tableHeader>
          <el-button
            size="default"
            type="success"
            class="ml10"
            @click="openAddUser()"
            v-auth="'system:user:add'"
            :icon="CirclePlus"
          >
            {{ $t("message.commonBtn.add") }}
          </el-button>
          <el-button type="primary" plain @click="batchAdd" size="default" v-auth="'system:user:add'" :icon="Upload">
            {{ $t("message.commonBtn.batchImport") }}
          </el-button>
        </template>
        <template #operation="scope">
          <el-space>
            <el-button size="small" text type="primary" @click="openEditUser(scope.row)" v-auth="'system:user:update'">
              <el-icon><Edit /></el-icon>
              {{ $t("message.commonBtn.edit") }}
            </el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <el-button text size="small" type="primary">
                  <el-icon><ArrowDownBold /></el-icon>
                  {{ $t("message.commonInfo.more") }}
                </el-button>
              </span>
              <template #dropdown>
                <el-dropdown-menu v-auth="'system:user:update'">
                  <el-dropdown-item @click="grantRole(scope.row)">
                    <el-icon><Lock /></el-icon>
                    {{ $t("message.userOperation.grantRole") }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="resetUserPwd(scope.row)">
                    <el-icon><RefreshLeft /></el-icon>
                    {{ $t("message.userOperation.resetPassword") }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="unlockUser(scope.row)">
                    <el-icon><Unlock /></el-icon>
                    {{ $t("message.userOperation.unLockUser") }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="delUser(scope.row)" divided>
                    <el-icon><Delete /></el-icon>
                    {{ $t("message.commonBtn.delete") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </ProTable>
      <EditUser ref="editUserRef" @refresh="handleQuery" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="SysUser">
import userApi from "@/api-services/apis/system/userApi";
import dictDataApi from "@/api-services/apis/system/dictDataApi";
import { SysUser, DictData, SysOrg } from "@/api-services/models/system";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { useI18n } from "vue-i18n";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { ElMessageBox } from "element-plus";
import { feature } from "@/utils/axios-utils";
import { ArrowDownBold, CirclePlus, Delete, Edit, Lock, RefreshLeft, Unlock, Upload } from "@element-plus/icons-vue";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import { EditUserProps } from "./component/editUser.vue";
import { useOrgStore } from "@/stores/modules/org";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
const EditUser = defineAsyncComponent(() => import("./component/editUser.vue"));
const ImportExcel = defineAsyncComponent(() => import("@/components/ImportExcel/index.vue"));
// 定义变量内容
const { t } = useI18n();
const treeFilter = ref<InstanceType<typeof TreeFilter> | null>(null);

interface InitParam {
  orgId: number;
}
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<InitParam>({ orgId: 0 });
// 获取 ProTable 元素
const proTableRef = ref<ProTableInstance>();
const genderData = ref<Array<DictData.SysDictData>>([]);
const orgTree = ref<Array<SysOrg.OrgSimpleInfo>>([]);
const orgStore = useOrgStore();
/** 部门切换 */
const changeTreeFilter = (val: number) => {
  proTableRef.value!.pageable.pageIndex = 1;
  initParam.orgId = val;
};

const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysUser.SysUser>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysUser.SysUser>[] = [
  { prop: "account", label: t("message.sysUser.account") },
  {
    prop: "name",
    label: t("message.sysUser.name"),
    search: { el: "input", props: { placeholder: t("message.userPlaceholder.name") } }
  },
  { prop: "orgName", label: t("message.sysUser.organization") },
  { prop: "phone", label: t("message.sysUser.phone") },
  {
    prop: "status",
    label: t("message.sysUser.status"),
    render: scope => {
      return (
        <el-switch
          v-auth="system:user:changeStatus"
          model-value={scope.row.status}
          active-text={scope.row.status ? t("message.userOperation.enable") : t("message.userOperation.disable")}
          active-value="enable"
          inactive-value="disable"
          onClick={() => changeStatus(scope.row)}
        />
      );
    }
  },
  {
    prop: "gender",
    label: t("message.sysUser.gender"),
    render: scope => {
      let data = genderData.value.filter(item => item.value == scope.row.gender)[0];
      return (
        <el-tag size={data?.tagSize} type={data?.tagType}>
          {data?.name}
        </el-tag>
      );
    }
  },
  { prop: "operation", label: t("message.userOperation.oper"), fixed: "right" }
];
// 查询操作
const handleQuery = async () => {
  proTableRef.value?.getTableList();
};
const queryGenderType = async () => {
  let [err, res] = await feature(dictDataApi.getDatalistByType("Gender"));
  if (err) {
    NotificationError(err.message);
  } else {
    genderData.value = res?.data.data ?? [];
  }
};
const queryOrgTree = async () => {
  orgTree.value = await orgStore.orgTreeGet;
};
watchEffect(async () => {
  queryGenderType();
  queryOrgTree();
});
const editUserRef = ref<InstanceType<typeof EditUser> | null>(null);
// 打开新增页面
function openAddUser() {
  const param: EditUserProps = {
    title: t("message.userOperation.addUser"),
    userData: {},
    orgData: orgTree.value,
    genderData: genderData.value
  };
  editUserRef.value?.openDialog(param);
}

// 打开编辑页面
const openEditUser = (row: SysUser.SysUser) => {
  const param: EditUserProps = {
    title: t("message.userOperation.editUser"),
    userData: row,
    orgData: orgTree.value,
    genderData: genderData.value
  };
  editUserRef.value?.openDialog(param);
};

// 删除
const delUser = (row: SysUser.SysUser) => {
  ElMessageBox.confirm(`${t("message.userAlter.isDeleteUser")}【${row.account}】?`, t("message.userAlter.alter"), {
    confirmButtonText: t("message.userAlter.confirm"),
    cancelButtonText: t("message.userAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      let ids = [{ id: row.id }];
      const [err] = await feature(userApi.delete(ids));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess(t("message.userAlter.deleteSuccess"));
        handleQuery();
      }
    })
    .catch();
};
// 修改状态
const changeStatus = async (row: SysUser.SysUser) => {
  let status = row.status;
  let mes: string;
  if (status === "enable") {
    mes = `${t("message.userAlter.disableUser")}【${row.account}】`;
  } else {
    mes = `${t("message.userAlter.enableUser")}【${row.account}】`;
  }
  ElMessageBox.confirm(mes, t("message.userAlter.alter"), {
    confirmButtonText: t("message.userAlter.confirm"),
    cancelButtonText: t("message.userAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(userApi.changeStatus({ id: row.id! }));
      if (err) {
        NotificationError(err.message);
      } else {
        row.status = status === "enable" ? "disable" : "enable";
        //handleQuery();
        NotificationSuccess(t("message.userAlter.changeStatus"));
      }
    })
    //取消动作
    .catch(() => {
      //不做处理
    });
};

// 重置密码
const resetUserPwd = async (row: SysUser.SysUser) => {
  ElMessageBox.confirm(`${t("message.userAlter.isResetPassword")}'【${row.account}】?`, t("message.userAlter.alter"), {
    confirmButtonText: t("message.userAlter.confirm"),
    cancelButtonText: t("message.userAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(userApi.resetPassword({ id: row.id! }));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess(t("message.userAlter.resetSuccess"));
      }
    })
    .catch(() => {
      //不做处理
    });
};
const grantRole = (row: SysUser.SysUser) => {
  //grantRoleRef.value?.openDialog(row);
  console.log(row);
};
const unlockUser = async (row: SysUser.SysUser) => {
  const [err, res] = await feature(userApi.unLockUser({ id: row.id! }));
  if (err) {
    NotificationError(err.message);
  } else {
    NotificationSuccess(res.message);
  }
};

// 批量添加用户
const importExcelRef = ref<InstanceType<typeof ImportExcel>>(); //ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: t("message.sysUser.user"),
    tempApi: userApi.templateDownload,
    importApi: userApi.batchImport,
    //getTableList: proTable.value?.getTableList;
    errorDownloadApi: userApi.errorFileDownload
  };
  importExcelRef.value?.acceptParams(params);
};
</script>

<style lang="scss" scoped></style>
